<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人资料</span>
        </div>
      </template>

      <div v-if="loading" class="loading">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>加载中...</span>
      </div>

      <div v-else-if="userProfile" class="profile-info">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="用户ID">
            {{ userProfile.id }}
          </el-descriptions-item>
          <el-descriptions-item label="用户名">
            {{ userProfile.username }}
          </el-descriptions-item>
          <el-descriptions-item label="邮箱">
            {{ userProfile.email }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="actions">
          <el-button @click="$router.push('/')">
            返回首页
          </el-button>
          <el-button type="danger" @click="logout">
            退出登录
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import api from '../services/api'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'

export default {
  name: 'Profile',
  components: {
    Loading
  },
  data () {
    return {
      userProfile: null,
      loading: true
    }
  },
  async mounted () {
    await this.fetchUserProfile()
  },
  methods: {
    async fetchUserProfile () {
      try {
        this.loading = true
        const response = await api.getUserProfile()
        this.userProfile = response.data
      } catch (error) {
        console.error('Fetch profile error:', error)
        ElMessage.error('获取用户信息失败')
        this.$router.push('/login')
      } finally {
        this.loading = false
      }
    },

    logout () {
      localStorage.removeItem('user')
      localStorage.removeItem('token')
      ElMessage.success('已退出登录')
      this.$router.push('/login')
    }
  }
}
</script>

<style scoped>
.profile-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60vh;
}

.profile-card {
  width: 500px;
}

.card-header {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
}

.loading {
  text-align: center;
  padding: 40px 0;
}

.loading .el-icon {
  margin-right: 8px;
}

.profile-info {
  padding: 20px 0;
}

.actions {
  margin-top: 30px;
  text-align: center;
}

.actions .el-button {
  margin: 0 10px;
}
</style>
